/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.iprange.info;

import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Iprangeuser;
import cn.net.greenet.db.bean.IprangeuserRange;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * 从数据库中获取IP地址段用户信息（目前只支持IPV4地址）
 *
 * @author liangdelin
 */
public class GetIpRangeUserInfo {

    private static Map<String, List<IprangeuserRange>> ipRange = new HashMap<>();

    /**
     * @return the ipRange
     */
    public static Map<String, List<IprangeuserRange>> getIpRange() {
        return ipRange;
    }

    /**
     * @param aIpRange the ipRange to set
     */
    public static void setIpRange() {
        getUserIpRangFromDB();
    }

    /**
     * 从数据库中获取IP地址段信息
     */
    public static void getUserIpRangFromDB() {
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        session.clear();
        Iprangeuser ipUserRange = null;
        List l = session.createQuery("FROM Iprangeuser").list();
        for (int i = 0; i < l.size(); i++) {
            ipUserRange = (Iprangeuser) l.get(i);
            Query query = session.createQuery("Select ip FROM IprangeuserRange As ip where ip.iprangeuser.id = :id");
            query.setParameter("id", ipUserRange.getId());
            List<IprangeuserRange> ll = (List<IprangeuserRange>) query.list();
            ipRange.put(ipUserRange.getName(), ll);
        }
        session.close();
    }

}
